package com.leyou.service.impl;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.dto.SpecGroupDTO;
import com.leyou.dto.SpecParamDTO;
import com.leyou.mapper.SpecGroupMapper;
import com.leyou.pojo.SpecGroup;
import com.leyou.pojo.SpecParam;
import com.leyou.service.SpecGroupService;
import com.leyou.service.SpecParamService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author jshstart
 * @creat 2020-12-09 17:21
 */
@Service
public class SpecGroupServiceImpl extends ServiceImpl<SpecGroupMapper, SpecGroup> implements SpecGroupService {
    @Autowired
    private SpecParamService specParamService;

    /**
     * 根据分类id查询规格组及对应的规格参数
     * @param id
     * @return
     */
    @Override
    public List<SpecGroupDTO> queryGroupParamByQCategoryId(Long id) {
        List<SpecGroup> specGroupList = query().eq("category_id", id).list();
        List<SpecGroupDTO> specGroupDTOList = SpecGroupDTO.convertEntityList(specGroupList);
        List<SpecParamDTO> specParamDTOList = specParamService.querySpecParamDTOByCondition(id, null, null);

            Map<Long, List<SpecParamDTO>> listMap = specParamDTOList.stream().collect(Collectors.groupingBy(SpecParamDTO::getGroupId));
        for (SpecGroupDTO specGroupDTO : specGroupDTOList) {
            if (listMap.containsKey(specGroupDTO.getId())){
                specGroupDTO.setParams( listMap.get(specGroupDTO.getId()));
            }
        }
        //最好不要在for循环中进行sql查询
//        List<SpecGroupDTO> list=new ArrayList<>();
//        for (SpecGroup specGroup : specGroupList) {
//            List<SpecParam> specParamList=specParamService.queryByCategoryIdByGroupId(specGroup.getId(),id);
//           SpecGroupDTO  specGroupDTO = new SpecGroupDTO(specGroup);
//            List<SpecParamDTO> specParamDTOList = specParamList.stream().map(SpecParamDTO::new).collect(Collectors.toList());
//            specGroupDTO.setParams(specParamDTOList);
//            list.add(specGroupDTO);
//        }

        return specGroupDTOList;
    }
}
